package jumpingnotes.dao.hibernate;

import java.util.List;

import jumpingnotes.dao.FriendDao;
import jumpingnotes.model.entity.Friend;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

public class FriendHibernateDao extends GenericHibernateDao<Friend> implements FriendDao
{
	public FriendHibernateDao()
	{
		super(Friend.class);
	}

	@SuppressWarnings("unchecked")
	public boolean isFriend(final int memberId1, final int memberId2)
	{
		return (Boolean) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session
						.createQuery("select distinct f from Friend f where " +
								"(f.memberByMemberIdFrom.memberId=:memberId1 and f.memberByMemberIdTo.memberId=:memberId2)" +
								" or (f.memberByMemberIdFrom.memberId=:memberId2 and f.memberByMemberIdTo.memberId=:memberId1)");
				query.setInteger("memberId1", memberId1);
				query.setInteger("memberId2", memberId2);
				return (query.list().size() > 0);
			}
		});
	}

	@SuppressWarnings("unchecked")
	public List<Friend> findFriendFromByMemberId(final int memberId, final int firstResult, final int maxResults)
	{
		return (List<Friend>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session
						.createQuery("select distinct f from Friend f where f.memberByMemberIdFrom.memberId=:memberId");
				query.setInteger("memberId", memberId);

				if (firstResult >= 0)
					query.setFirstResult(firstResult);
				if (maxResults > 0)
					query.setMaxResults(maxResults);

				return query.list();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public List<Friend> findFriendToByMemberId(final int memberId, final int firstResult, final int maxResults)
	{
		return (List<Friend>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session
						.createQuery("select distinct f from Friend f where f.memberByMemberIdTo.memberId=:memberId");
				query.setInteger("memberId", memberId);

				if (firstResult >= 0)
					query.setFirstResult(firstResult);
				if (maxResults > 0)
					query.setMaxResults(maxResults);

				return query.list();
			}
		});
	}
}
